package com.crowntit.domain.trade.service.lock.filter;

import com.crowntit.domain.trade.adapter.repository.ITradeRepository;
import com.crowntit.domain.trade.model.entity.GroupBuyActivityEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleBackEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleCommandEntity;
import com.crowntit.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.crowntit.types.design.framework.link.model2.handler.ILogicHandler;
import com.crowntit.types.enums.ResponseCode;
import com.crowntit.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class TradeLockUserTakeLimitFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleBackEntity apply(TradeLockRuleCommandEntity requestParam, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {

        Integer takeOrderCount = repository.queryUserTakeOrderCount(requestParam.getUserId(), requestParam.getActivityId());
        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();
        if (null != groupBuyActivity.getTakeLimitCount() && takeOrderCount >= groupBuyActivity.getTakeLimitCount()){
            log.info("用户参加活动次数上限，用户: {}，活动: {}", requestParam.getUserId(), requestParam.getActivityId());
            throw new AppException(ResponseCode.E0003.getCode(), ResponseCode.E0103.getInfo());
        }

        dynamicContext.setUserTakeLimitCount(takeOrderCount);
        return next(requestParam, dynamicContext);
    }
}